package com.juzipi.demo.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juzipi.demo.pojo.User;
import com.juzipi.demo.tools.LoginDto;
import com.juzipi.demo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//抽象认证处理过滤器?

public class JsonAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    @Autowired
    private ObjectMapper objectMapper;


    public JsonAuthenticationFilter() {
        //路径请求匹配器
        super(new AntPathRequestMatcher("/login","POST"));
    }



    //尝试身份验证
    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        //从输入流中获取到登陆的信息
        try {
            LoginDto loginUser = objectMapper.readValue(httpServletRequest.getInputStream(), LoginDto.class);
//            return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUsername(),loginUser.getPassword()));
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword());
            //认证吧
            Authentication authenticate = getAuthenticationManager().authenticate(token);
            //如果已认证，获取到用户信息，生成token
            if (authenticate.isAuthenticated()){
                User user = (User) authenticate.getPrincipal();
                String jwtToken = JwtUtil.getToken(user);
                user.setToken(jwtToken);
//                User user = (User) authenticate.getPrincipal();
//                Token tokens = Token.getInstance();
//                tokens.setToken(UUID.randomUUID().toString());
//                tokens.setUserId(user.getId());
//                tokenService.createToken(tokens);
//                user.setToken(tokens.getToken());
                //大概就是生成token然后设置给用户的扩展字段token
            }
            return authenticate;
        } catch (IOException | AuthenticationException e) {
            e.printStackTrace();
            return null;
        }


    }


}
